<?php
/**
 * Created by PhpStorm.
 * User: liyang
 * Date: 2017/12/4  Time: 下午4:35
 * Description:用户信息
 */

use Service\App;
use Service\UserService;
use Yaf\Session;
use Yaf\Registry;
use Illuminate\Database\Capsule\Manager as Capsule;
use Rester\Validator;
use Wxxiong6\WxxLogger\WxxLogger as Logger;
use IdCard\IdCard;
use Service\ConsulationService;

class UserController extends BaseController
{

    /**
     * 获取用户基本信息
     */
    public function infoAction()
    {
        $id = $this->header['uid'];//用户ID
        if (empty($id)) {
            $this->callback('', MISS_REQUEST_PARAMS, '缺少参数,参数为空');
        }
        $userInfo = UserModel::query()->select(UserService::getInstance()->fileds)->where('id', $id)->first();
        if (empty($userInfo['id'])) {
            $this->callback('', MISS_REQUEST_PARAMS, '没有此用户');
        } else {
            $userInfo = $userInfo->toArray();
        }
        $callBackByUser = UserService::getInstance()->getUserInfo($userInfo);

        $this->callback($callBackByUser);
    }

    /**
     * 修改密码
     */
    public function resetPwdAction()
    {
        $id = $this->header['uid'];
        $oldPassword = $this->getRequest()->getParam('oldPassword');
        $newPassword = $this->getRequest()->getParam('newPassword');
        $vData = [
            'oldPassword' => $oldPassword,
            'newPassword' => $newPassword,
        ];
        $rules = [
            'oldPassword' => 'required',
            'newPassword' => 'required',
        ];
        if (!Rester\Validator::validators($rules, $vData)) {
            $this->callback([], '1002', '参数不正确!');
        }

        $user = UserModel::select(['id', 'pwd'])->where('id', $id)->first();
        if ($oldPassword != $user->pwd) {
            $this->callback([], '1004', '原密码不正确');
        }

        $user->pwd = $newPassword;
        if ($user->save()) {
            $this->callback([], '0000', '修改密码成功');
        } else {
            $this->callback([], '1004', '修改密码失败');
        }

    }

    /**
     * 手机号修改第一步
     */
    public function checkPhoneAction()
    {
        $oldPhone = $this->getRequest()->getParam('oldPhone');
        $code = $this->getRequest()->getParam('code');
        $data = [
            'oldPhone' => $oldPhone,
            'code' => $code
        ];
        $rules = [
            'oldPhone' => 'required|regex:/^1[34578][0-9]{9}$/',
            'code' => 'required'
        ];
        $validator = Validator::getInstance()->make($data, $rules);

        if ($validator->fails()) {
            $fails = $validator->failed();
            if (isset($fails['oldPhone'])) {
                $this->callback([], '0101', '请输入正确的手机号');
            } else {
                $this->callback([], '0101', '短信验证码不能为空');
            }
        }
        $oldPhoneKey = 'sms-code-modifierphone:' . $oldPhone;
        $smsCode = $this->redis->get($oldPhoneKey);
        if ($smsCode != $code) {
            $this->callback([], SMS_CODE_ERROR, '短信验证码输入错误');
        }

        $ttl = $this->redis->ttl($oldPhoneKey);
        if ($ttl + 300 < 3600 * 24) {
            $this->callback([], SMS_CODE_ERROR, '短信验证码失效，请重新获取');
        }
        $this->redis->del($oldPhoneKey);


        $this->redis->setex('record-old-phone:' . $this->header['uid'], 24 * 3600, $oldPhone);


        $this->callback([], '0000', '原手机号验证通过');

    }

    /**
     * 手机号修改第二步
     */
    public function resetPhoneAction()
    {
        $id = $this->header['uid'];
        $newPhone = $this->getRequest()->getParam('newPhone');
        $code = $this->getRequest()->getParam('code');
        $data = [
            'newPhone' => $newPhone,
            'code' => $code
        ];
        $rules = [
            'newPhone' => 'required|regex:/^1[34578][0-9]{9}$/',
            'code' => 'required'
        ];
        $validator = Validator::getInstance()->make($data, $rules);

        if ($validator->fails()) {
            $fails = $validator->failed();
            if (isset($fails['newPhone'])) {
                $this->callback([], '0101', '请输入正确的手机号');
            } else {
                $this->callback([], '0101', '短信验证码不能为空');
            }
        }
        $newPhoneKey = 'sms-code-modifierphone:' . $newPhone;
        $smsCode = $this->redis->get($newPhoneKey);
        if ($smsCode != $code) {
            $this->callback([], SMS_CODE_ERROR, '短信验证码输入错误');
        }

        $ttl = $this->redis->ttl($newPhoneKey);
        if ($ttl + 300 < 3600 * 24) {
            $this->callback([], SMS_CODE_ERROR, '短信验证码失效，请重新获取');
        }
        $this->redis->del($newPhoneKey);

        $checkPhone = UserModel::query()->where(['cellphone' => $newPhone])->first();
        if (!empty($checkPhone)) {
            $this->callback([], SMS_CODE_ERROR, '该手机号已注册');
        }
        if (RecordPhoneModel::query()->where(['cellphone' => $newPhone])->first()) {
            $this->callback([], '0400', '该手机号户已锁定');
            return;
        }
        $saveData['cellphone'] = $newPhone;
        $saveData['update_time'] = date('Y-m-d H:i:s');
        $modifierPhone = UserModel::where('id', $id)->update($saveData);
        if ($modifierPhone) {
            //记录用户修改前手机号
            $oldPhoneKey = 'record-old-phone:' . $id;
            $oldPhone = $this->redis->get($oldPhoneKey);
            if(!empty($oldPhone)) {
                $recordModel = RecordPhoneModel::query()->where(['cellphone' => $oldPhone])->first();
                if(empty($recordModel)) {
                    $recordModel = new RecordPhoneModel();
                    $recordModel->cellphone = $oldPhone;
                    $recordModel->create_at = date('Y-m-d H:i:s');
                    $recordModel->save();
                }
                $this->redis->del($oldPhoneKey);
            }

            $this->callback([], '0000', '手机号修改成功');
        }
        $this->callback([], '1004', '手机号修改失败');

    }

    /**
     * 修改个人用户信息
     */
    public function editUserAction()
    {
        $id = $this->header['uid'];
        $params = $this->getRequest()->getParams();
        if (empty($params)) {
            $this->callback([], MISS_REQUEST_PARAMS, '缺少参数,参数为空');
        }
        $validator = UserModel::validatorUser($params);
        if ($validator['validator']->fails()) {
            Logger::info('输入不合法：' . var_export($validator['validator']->failed(), true));
            $this->callback([], MISS_REQUEST_PARAMS, '输入不合法');
        }
        $params['from_mobile'] = 1;
        $params['first_edit'] = 1;
        $params['update_time'] = date('Y-m-d H:i:s');
        $userData = UserModel::select('identity_id', 'relation_address', 'custodian_identity_id', 'promise', 'recent_one_years_reincome', 'recent_one_financial_assets')->where('id', $id)->first();
        if ($params['type'] == 1) {

            if($params['step'] ==2) {
                if (!$this->checkId($params['custodian_name'], $params['custodian_identity_id'])) {
                    $this->callback(['status' => 0], '0400', '监护人实名认证失败，请检查输入信息');
                    return;
                }
                $this->redis->setex('custodian_identity_id:' . $id, 24 * 3600, $params['custodian_identity_id']);

                if(isset($userData['promise']) && $userData['promise'] ==2 ){
                    $params['is_private_fund_status'] = 2;
                }
            }
            if ($params['step'] == 3 && isset($params['promise']) && $params['promise'] ==2) {
                $idcard = new IdCard();
                $dateBrithday = $idcard->getIDCardInfo($userData['identity_id']);
                if($dateBrithday['isAdult'] !=1) {
                    $params['is_private_fund_status'] = 2;//是否完善私募合规信息 1：否 2：是
                } else {
                    $oldPhoneKey = 'custodian_identity_id:' . $id;
                    $oldPhone = $this->redis->get($oldPhoneKey);
                    if(!empty($oldPhone)) {
                        $params['is_private_fund_status'] = 2;
                    }
                    $this->redis->del($oldPhoneKey);
                }
            }

            unset($params['step'], $params['type']);
            if (!empty($validator['data'])) {
                UserPersonInfoModel::where('u_id', $id)->update($validator['data']);
                $diffArr = array_intersect_key($validator['data'], $params);
                if (!empty($diffArr)) {
                    foreach ($diffArr as $k => $v) {
                        unset($params[$k]);
                    }
                }
            }

            if (UserModel::where('id', $id)->update($params)) {
                $this->callback([], '0000', '修改成功');
            }

        } else {
            if ($params['type'] == 2) {

                $orgRes = UserOrgInfoModel::select('legal_person_card','org_type', 'fill_num','auth_person_name', 'auth_person_card')->where('u_id', $id)->first();

                if (isset($orgRes['org_type']) && $orgRes['org_type'] ==1
                        && !empty($orgRes['legal_person_card'])
                        && isset($params['recent_one_years_reincome']))  {
                    $params['is_private_fund_status'] = 2;//是否完善私募合规信息 1：否 2：是
                }
                if (isset($orgRes['org_type']) && $orgRes['org_type'] ==2
                    && !empty($orgRes['legal_person_card'])
                    && !empty($userData['relation_address'])
                    && !empty($orgRes['fill_num'])
                    && isset($params['promise']) && $params['promise'] ==2)  {
                    $params['is_private_fund_status'] = 2;//是否完善私募合规信息 1：否 2：是
                }

                unset($params['step'], $params['type']);
                if (!empty($validator['data'])) {
                    UserOrgInfoModel::where('u_id', $id)->update($validator['data']);
                    $diffArr = array_intersect_key($validator['data'], $params);
                    if (!empty($diffArr)) {
                        foreach ($diffArr as $k => $v) {
                            unset($params[$k]);
                        }
                    }
                }

                if (UserModel::where('id', $id)->update($params)) {
                    $this->callback([], '0000', '修改成功');
                }
            }
        }

        $this->callback([], '1004', '修改失败');
    }

    /**
     * 修改机构用户信息
     */
    public function editOrgUserAction()
    {
        $id = $this->header['uid'];
        $params = $this->getRequest()->getParams();
        if (empty($params)) {
            $this->callback([], MISS_REQUEST_PARAMS, '缺少参数,参数为空');
        }

        $validator = UserModel::validatorOrgUser($params);
        if ($validator->fails()) {
            Logger::info('输入不合法：' . var_export($validator->failed(), true));
            $this->callback([], MISS_REQUEST_PARAMS, '输入不合法');
        }
        $checkCard = false;
        $orgRes = UserOrgInfoModel::select('org_type','legal_person_name','legal_person_card','auth_person_name', 'auth_person_card', 'fill_num')->where('u_id', $id)->first();
        $userData = UserModel::select('promise')->where('id', $id)->first();
        if($params['step'] ==1) {
            if (!$this->checkId($params['legal_person_name'], $params['legal_person_card'])) {
                $this->callback(['status' => 0], '0400', '法定代表人实名认证失败，请检查输入信息');
                return;
            }
            if (!$this->checkId($params['auth_person_name'], $params['auth_person_card'])) {
                $this->callback(['status' => 0], '0400', '授权代表人实名认证失败，请检查输入信息');
                return;
            }

            if(isset($orgRes['auth_person_card']) && $orgRes['auth_person_card'] != $params['auth_person_card']) {
                ConsulationService::clearPrivateStatus($id);
            }

            if(isset($orgRes['org_type']) && $orgRes['org_type'] ==2 &&
                !empty($orgRes['fill_num']) && $userData['promise'] ==2 ){
                $status['is_private_fund_status'] = 2;
            }
            if(isset($orgRes['org_type']) && $orgRes['org_type'] ==1 &&
                !empty($params['legal_person_name']) && $userData['promise'] ==2 ){
                $status['is_private_fund_status'] = 2;
            }
            if((isset($orgRes['auth_person_name']) && $orgRes['auth_person_name'] != $params['auth_person_name']) ||
                isset($orgRes['auth_person_card']) && $orgRes['auth_person_card'] != $params['auth_person_card']) {
                $checkCard = true;
            }
        }
        if($params['step'] ==2) {
            if(!empty($orgRes['legal_person_card']) && $userData['promise'] ==2 ){
                $status['is_private_fund_status'] = 2;
            }
        }


        unset($params['step']);
        $params['update_time'] = date('Y-m-d H:i:s');
        if (UserOrgInfoModel::where('u_id', $id)->update($params)) {
            if($checkCard) {
                $msRes = UserMSModel::select('id', 'status')->where('user_id', $id)->orderBy('id', 'desc')->first();
                if(!empty($msRes)) {
                    $msRes->status = 1;
                    $msRes->save();
                }

            }
            if(!empty($status)){
                UserModel::where('id', $id)->update($status);
            }
            $this->callback([], '0000', '修改成功');
        }
        $this->callback([], '1004', '修改失败');
    }
    protected function checkId($name, $idNum)
    {
        $idcard = new IdCard();
        if (!$idcard->isChinaIDCard($idNum)) {
            return 0;
        }
        $check = rzb($name, $idNum) ? 1 : 0;
        return $check;
    }
    /**
     * 查询用户信息
     */
    public function getUserAction()
    {
        $id = $this->header['uid'];
        $step = $this->getRequest()->getParam('step');
        $type = $this->getRequest()->getParam('type');
        if (empty($step) || empty($type) || empty($id)) {
            $this->callback([], MISS_REQUEST_PARAMS, '缺少参数,参数为空');
        }
        $callBackByUser = UserService::getInstance()->getUserByStep($step, $type, $id);

        foreach ($callBackByUser as &$v) {
            if(isset($v)) {
                $v = strval($v) ;
            }
        }

        $this->callback($callBackByUser);
    }

    /**
     * 查询机构信息
     */
    public function getOrgUserAction()
    {
        $id = $this->header['uid'];
        $step = $this->getRequest()->getParam('step');
        if (empty($step) || empty($id)) {
            $this->callback([], MISS_REQUEST_PARAMS, '缺少参数,参数为空');
        }
        $callBackByUser = UserService::getInstance()->getOrgUserByStep($step, $id);

        $this->callback($callBackByUser);

    }

    public function sendsmsAction()
    {
        $phone = $this->getRequest()->getParam('cellphone');
        $type = $this->getRequest()->getParam('type');
        $data = [
            'phone' => $phone,
            'type' => $type,
        ];
        $rules = [
            'type' => 'required|integer|max:6|min:1',
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/'
        ];
        $validator = Validator::getInstance()->make($data, $rules);

        if ($validator->fails()) {
            $fails = $validator->failed();
            if (isset($fails['type'])) {
                $this->callback([], '0101', 'type校验错误');
            } else {
                $this->callback([], '0101', '手机号码错误');
            }

            return;
        }


        $date = date('Y-m-d');
        $key = 'sms:' . $phone . '-' . $date;
        $key2 = 'sms-list:' . $phone . '-' . $date;
        $redis = $this->redis;

        $total = intval($redis->get($key));
        if ($total >= SMS_COUNT_LIMIT) {
            $this->callback([], '0103', '验证码发送次数已超出当日允许的最大次数' . SMS_COUNT_LIMIT . '次');
            return;
        }

        $lock = $redis->setnx('lock-' . $phone, 1);
        $redis->expire('lock-' . $phone, 5);
        if (!$lock) {
            $this->callback([], '0104', '您点的太快了');
            return;
        }


        $record = $redis->lRange($key2, -3, -1);
        if ($record && count($record) == 2) {
            $diff = time() - min($record);
            if ($diff < 600) {
                $this->callback([], '0104', '十分钟内验证码发送次数不得超过3次');
                return;
            }
        }


        $user = UserModel::query()->where(['cellphone' => $phone])->select()->first();
        $code = generateSMSCode();
        $send = false;

        if ($type == 1) {
            if ($user) {
                $this->callback([], '0102', '用户已注册');
                return;
            }

            $msg = "【坤元资产】尊敬的用户，您正在用手机注册坤元资产账号，您的验证码为：{$code}(有效期五分钟)，请勿向他人泄露验证码。";
            $send = sms($phone, $msg);
            if ($send) {
                $redis->setex('sms-code-register:' . $phone, 24 * 3600, $code);
            }
        } elseif ($type == 4) {// 忘记密码
            if (!$user) {
                $this->callback([], '0102', '用户未注册');
                return;
            }

            $msg = "【坤元资产】尊敬的用户，您正在用手机重置，您的验证码为：{$code}(有效期五分钟)，请勿向他人泄露验证码。";
            $send = sms($phone, $msg);
            if ($send) {
                $redis->setex('sms-code-forgetpwd:' . $phone, 24 * 3600, $code);
            }
        } elseif ($type == 5) {// 修改手机号码第一步
            if (!$user) {
                $this->callback([], '0102', '用户未注册');
                return;
            }

            $msg = "【坤元资产】尊敬的用户，您正在用手机修改，您的验证码为：{$code}(有效期五分钟)，请勿向他人泄露验证码。";
            $send = sms($phone, $msg);
            if ($send) {
                $redis->setex('sms-code-modifierphone:' . $phone, 24 * 3600, $code);
            }
        }
        elseif ($type == 6) {// 修改手机号码二步 新手机号

            $msg = "【坤元资产】尊敬的用户，您正在用手机修改，您的验证码为：{$code}(有效期五分钟)，请勿向他人泄露验证码。";
            $send = sms($phone, $msg);
            if ($send) {
                $redis->setex('sms-code-modifierphone:' . $phone, 24 * 3600, $code);
            }
        }
        if ($send) {
            $redis->setex($key, 3600 * 24, $total + 1);
            $redis->lPush($key2, time());
            $redis->expireAt($key2, strtotime($date) + 3600 * 24);
            $this->callback([], '0000', '发送成功');
        } else {
            $this->callback([], '0400', '发送失败');
        }
    }

    /**
     * 登录
     */
    public function loginAction()
    {
        $cellphone = trim($this->getRequest()->getParam('cellphone'));
        $password = trim($this->getRequest()->getParam('password'));

        if (!$cellphone) {
            $this->callback([], LOGIN_CELLPHONE_NULL, "手机号不能为空");
        }

        $rules = [
            'cellphone' => 'required|regex:/^1[34578][0-9]{9}$/'
        ];
        $validator = Validator::getInstance()->make(['cellphone' => $cellphone], $rules);
        if ($validator->fails()) {
            $this->callback([], LOGIN_CELLPHONE_WRONG, "手机号码错误");
        }

        if (!$password) {
            $this->callback([], LOGIN_PASSWORD_NULL, "密码不能为空");
        }

        try {
            $result = UserService::getInstance()->login($cellphone, $password);
            UserService::getInstance()->loginErrorCount($cellphone, $clear = true);
        } catch (Exception $e) {
            $failed_count = 1;
            if ($e->getCode() != LOGIN_UNKNOWN_USERNAME) {
                $failed_count = UserService::getInstance()->loginErrorCount($cellphone);
            }
            $this->callback(['failed_count' => $failed_count], strval($e->getCode()), $e->getMessage());
        }

        $this->callback($result);
    }

    /**
     * 重置密码
     */
    public function resetpasswdAction()
    {
        $cellphone = trim($this->getRequest()->getParam('cellphone'));
        $sms_code = trim($this->getRequest()->getParam('sms_code'));
        $password = trim($this->getRequest()->getParam('password'));

        $vdata = [
            'cellphone' => $cellphone,
            'sms_code' => $sms_code,
            'password' => $password,
        ];
        $rules = [
            'cellphone' => 'required',
            'sms_code' => 'required',
            'password' => 'required',
        ];
        if (!Rester\Validator::validators($rules, $vdata)) {
            $this->callback([], '1002', '参数不正确!');
        }

        $verify = UserService::getInstance()->checkVerifyCode($cellphone, $sms_code, $type = 4);
        if (!$verify['status']) {
            $this->callback([], $verify['code'], $verify['msg']);
        }

        $result = UserModel::select(['id', 'pwd'])->where('cellphone', $cellphone)->get();
        if ($result->isEmpty()) {
            $this->callback([], '1003', '用户未注册');
        }

        $user = $result->first();
        $user->pwd = $password;
        if ($user->save()) {
            $this->callback([], '0000', '重置密码成功');
        } else {
            $this->callback([], '1004', '重置密码失败');
        }
    }

    public function qualifiedAction()
    {
        $header = $this->header;
        if (!isset($header['uid'])) {
            $this->callback(['status' => 0], '0401', '未登录');
            return;
        }

        $uid = $header['uid'];
        /** @var UserModel $user */
        $user = UserModel::query()->find($uid);
        if (!$user) {
            $this->callback(['status' => 0], '0403', '找不到用户');
            return;
        }
        $user->investor = 1;
        $user->save();
        //更新缓存信息
        UserService::getInstance()->deleteUserInfoCache($uid);

        $this->callback(['status' => 1]);
    }

    /**
     * 验证token 是否已过期
     */
    public function checkTokenAction()
    {
        $uid = App::checkToken();
        $this->callback(['uid' => $uid ? $uid : "0"], '0000', '请求成功');
    }

    public function logoutAction()
    {
        App::deleteToken(App::$header['token']);
        $this->callback([], '0000', '退出成功');
    }

    public function uploadAction()
    {
        $id = $this->header['uid'];//用户ID
        if (empty($id)) {
            $this->callback('', MISS_REQUEST_PARAMS, '缺少参数uid,参数为空');
        }
        $data = [
            'category' => $this->getRequest()->getParam('category'),
        ];
        $rules = [
            'category' => 'required|min:1|max:4',
        ];
        $validator = Validator::getInstance()->make($data, $rules);
        if ($validator->fails()) {
            $this->callback([], '0400', '参数错误');
            return;
        }

        $fileField = 'file';
        if (!isset($_FILES[$fileField])) {
            $this->callback([], '0400', '未上传附件');
            return;
        }
        $name = $_FILES[$fileField]['name'];
        $tmp_name = $_FILES[$fileField]['tmp_name'];
        $size = $_FILES[$fileField]['size'];
        $error = $_FILES[$fileField]['error'];
        if ($error !== UPLOAD_ERR_OK) {
            $this->callback([], '0400', '上传失败');
            return;
        }
        $ext = stristr($name, '.');

        $rootDirectory = getUploadDir();

        if ($data['category'] == 1) { //身份证照片
            $dir = '/Public/data/uploads/identity_card/';

            if (($msc = $this->msCheck($size, $ext)) !== true) {
                $this->callback([], '0400', $msc);
                return;
            }
        } elseif ($data['category'] == 2) { //人脸识别图片
            $dir = '/shearphoto/shearphoto_common/file/shearphoto_file/';
            if (($msc = $this->msCheck($size, $ext)) !== true) {
                $this->callback([], '0400', $msc);
                return;
            }
        } elseif ($data['category'] == 3) { //营业执照图片
            $dir = '/Public/data/uploads/bls/';
        } elseif ($data['category'] == 4) { //用户头像
            $dir = '/Public/data/uploads/user_header_img/';
        }

        $date = date('Y-m-d') . '/';
        $dir = $dir . $date;
        if (!file_exists($rootDirectory . $dir)) {
            mkdir($rootDirectory . $dir, 0777, true);
        }

        $rename = time() . rand(10000, 99999);
        $path = $dir . $rename . $ext;   // 定义上传文件的存储位置
        $url = $path;
        $path = $rootDirectory . $path;

        if (is_uploaded_file($tmp_name)) {   // 判断上传是不是通过HTTP POST上传的
            if (!move_uploaded_file($tmp_name, $path)) {   // 执行文件上传操作
                $this->callback([], '0500', '附件上传失败');
                return;
            }
        }
        if ($data['category'] == 4) {
            if (!UserModel::where('id', $id)->update(['user_img'=>$url])) {
                $this->callback([], '0500', '附件地址保存失败');
                return;
            }
        }

        $this->callback(['url' => getUploadHost() . $url]);
        return;
    }

    protected function msCheck($size, $type)
    {
        $allow_type = array('.jpg', '.jpeg', '.gif', '.png', '.bmp'); //定义允许上传的类型

        if (!in_array($type, $allow_type)) {
            return '仅支持jpg,jpeg.gif,png,bmp格式';
        }

        $fileSize = strlen($size) / 1024;
        if ($fileSize > 2000) { // 大于2M 敏识规定
            return '图片不得大于2M';
        }

        return true;
    }

    public function idphotocheckAction()
    {
        $header = $this->header;
        if (!isset($header['uid'])) {
            $this->callback([], '0401', '未登录');
            return;
        }
        $uid = $header['uid'];
        $user = UserModel::query()->find($uid);

        $data = [
            'front' => parse_url($this->getRequest()->getParam('front'), PHP_URL_PATH),
            'back' => parse_url($this->getRequest()->getParam('back'), PHP_URL_PATH),
        ];
        $rules = [
            'back' => 'required',
            'front' => 'required',
        ];
        $validator = Validator::getInstance()->make($data, $rules);
        if ($validator->fails()) {
            $this->callback([], '0400', '参数错误');
            return;
        }
        /** @var UserMSModel $userMs */
        $userMs = UserMSModel::query()->where(['user_id' => $uid])->first();
        if (!$userMs) {
            $userMs = new UserMSModel();
            $userMs->user_id = $uid;
        }
        $userMs->fill(['img_path_front' => $data['front'], 'img_path_reverse' => $data['back']]);
        if (!file_exists($userMs->getRealFrontImgPath()) || !file_exists($userMs->getRealBackImgPath())) {
            $this->callback([], '0400', '文件不存在');
            return;
        }
        $data = $userMs->getPhotoData();
        $photoCardId = $data['card_id'] ?? '' ;
        //验证上传身份证照片，是否是本人
        $checkCardPhotoResult = UserService::getInstance()->checkCardPhoto($photoCardId, $user->identity_id, $user->id,  $user->type);
        if ($checkCardPhotoResult) {
            $data['status'] = 2;
        } else {
            $data['status'] = 1;
        }

        $record = new UserMSRecordModel();
        $record->u_id = $uid;
        $record->modify_time = date('Y-m-d H:i:s');
        $record->content = json_encode($data);

        $record->save();

        $userMs->fill($data);
        if ($data['status'] == 2) {
            $userMs->save();
            $this->callback();
        } else {
            $this->callback([], '0400', '认证失败');
        }


    }

    public function businesslicencephotoAction()
    {
        $header = $this->header;
        if (!isset($header['uid'])) {
            $this->callback([], '0401', '未登录');
            return;
        }
        $data = [
            'url' => $this->getRequest()->getParam('url'),
        ];
        $rules = [
            'url' => 'required',
        ];
        $validator = Validator::getInstance()->make($data, $rules);
        if ($validator->fails()) {
            $this->callback([], '0400', '参数错误');
            return;
        }

        $this->saveBlsPhoto($data['url']);

        $this->callback();
    }

    private function saveBlsPhoto($url)
    {
        $url = parse_url($url, PHP_URL_PATH);
        $uid = $this->header['uid'];
        /** @var UserOrgInfoModel $userInfo */
        $userInfo = UserOrgInfoModel::query()->where(['u_id' => $uid])->first();
        if (!$userInfo) {
            return;
        }

        $userInfo->bls_photo = $url;

        $userInfo->save();
    }

    public function idphotoAction()
    {
        $uid = $this->header['uid'];
        /** @var UserMSModel $userMs */
        $userMs = UserMSModel::query()->where(['user_id' => $uid])->first();
        $data = [
            'front' => '',
            'back' => '',
        ];
        if ($userMs && $userMs->isOK()) {
            $host = getUploadHost();
            $data = [
                'front' => $userMs->img_path_front ? $host . $userMs->img_path_front : '',
                'back' => $userMs->img_path_reverse ? $host . $userMs->img_path_reverse : '',
            ];
        }

        $this->callback($data);
    }
}